const app = getApp()
let isRefreshing = true
import { useUCenterStore } from '@/stores/uCenter'
const ucenter = useUCenterStore();
const loginFailErrorCodes = [
  '1201',
  '1202',
  '1203',
  '1205',
  '1206',
  '1207',
  '1208',
  '1209'
]
const uniRequest = (params = {}, url,method = 'GET') => {
  let data = params.query || {}
  const mpsessid =
    uni.getStorageSync('memberInfo') &&
    uni.getStorageSync('memberInfo').memberEncode
      ? uni.getStorageSync('memberInfo').memberEncode
      : ''
  let params_ = {
    mpsessid: mpsessid
  }
  return new Promise(async (resolve, reject) => {
    await uni.request({
      url: url,
      method: method,
      data: data,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        ...params_
      },
      success: async sucInfo => {
        let responseData = sucInfo['data']
        if (responseData.success) {
          return resolve(responseData)
        } else {
          if (loginFailErrorCodes.indexOf(responseData['errcode']) != -1) {            const pages = getCurrentPages() // 获取当前打开过的页面路由数组
            const currentPage = pages[pages.length - 1]
            let fullPath = currentPage.route
            if (Object.keys(currentPage.options).length) {
              fullPath = `/${currentPage.route}?${Object.keys(
                currentPage.options
              ).map(key => `${key}=${currentPage.options[key]}`)
                .join('&')}`
            }
            if (isRefreshing) {
              isRefreshing = false
              uni.removeStorageSync('memberInfo')
              ucenter.$patch({ 'memberInfo': {}})
              //存储当前路由地址，授权完毕回调
              ucenter.$patch({ 'redirectPath': fullPath})
              // 如果当前未有登录信息，弹窗时报未登录，有登陆信息则报异常用户信息
              
              uni.reLaunch({
                url: '/pages/auth/index'
              })
            } else {
              isRefreshing = true
            }
          } else {
            if (responseData['errcode'] != 1121 && data.showToast != 'noMsg') {
              uni.showToast({ title: responseData.msg, icon: 'none' })
            }
            return resolve(responseData)
          }
        }
      },
      fail: failInfo => {
        return reject(failInfo)
      },
      complete: finInfo => {
        let status = finInfo.statusCode
        switch (status) {
          case 403:
            uni.showToast({
              title: status + '错误，Sorry, 无权限操作。',
              icon: 'none'
            })
            return
          case 404:
            uni.showToast({
              title: status + '错误，Sorry, 服务不存在。',
              icon: 'none'
            })
            return
          case 500:
          case 502:
          case 503:
            uni.showToast({
              title: status + '错误，Sorry, 服务器异常。',
              icon: 'none'
            })
            return
          case 504:
            uni.showToast({
              title: status + '错误，Sorry, 请求超时。',
              icon: 'none'
            })
            return
          default:
            return
        }
      }
    })
  })
}

const uniGet = async (params = {}, url) => {
  return uniRequest(params, url,'GET')
}

const uniPost = async (params = {}, url) => {
  return uniRequest(params, url,'POST')
}

export const uniFetch = {
  uniGet,
  uniPost
}
